﻿using Engine;
using Engine.Graphics;
using Game;

namespace SAGhoul.ParticleSystem
{
	public class FloatingImageParticleSystem : ParticleSystem<FloatingImageParticleSystem.Particle>
	{
		public class Particle : Game.Particle
		{
			public float TimeToLive;
			public Vector3 Velocity;
			public Color BaseColor;
			public string Texture;
			public Vector2 pSize;
		}

		TexturedBatch3D m_batch;
		readonly Game.Random m_random = new();

		public FloatingImageParticleSystem(Vector3 position, Vector3 velocity, Vector2 size, Color color, float time, string texture)
			: base(1)
		{
			Particle obj = Particles[0];
			obj.IsActive = true;
			obj.Position = position;
			obj.TimeToLive = time;
			obj.Velocity = velocity + m_random.Vector3(0.75f) * new Vector3(1f, 0f, 1f) + 0.5f * Vector3.UnitY;
			obj.BaseColor = color;
			obj.Texture = texture;
			obj.pSize = size;
		}

		public override bool Simulate(float dt)
		{
			dt = MathUtils.Clamp(dt, 0f, 0.1f);
			float num = MathUtils.Pow(0.1f, dt);
			bool flag = false;
			for (int i = 0; i < Particles.Length; i++)
			{
				Particle particle = Particles[i];
				if (particle.IsActive)
				{
					flag = true;
					particle.TimeToLive -= dt;
					if (particle.TimeToLive > 0f)
					{
						particle.Velocity += new Vector3(0f, 0.5f, 0f) * dt;
						particle.Velocity *= num;
						particle.Position += particle.Velocity * dt;
						particle.Color = particle.BaseColor * MathUtils.Saturate(2f * particle.TimeToLive);
					}
					else
					{
						particle.IsActive = false;
					}
				}
			}
			return !flag;
		}

		public override void Draw(Camera camera)
		{
			Vector3 viewDirection = camera.ViewDirection;
			var right = Vector3.Normalize(Vector3.Cross(viewDirection, Vector3.UnitY));
			Vector3 down = -Vector3.Normalize(Vector3.Cross(right, viewDirection));
			for (int i = 0; i < Particles.Length; i++)
			{
				Particle particle = Particles[i];
				if (particle.IsActive)
				{
					float num = Vector3.Distance(camera.ViewPosition, particle.Position);
					float num2 = MathUtils.Saturate(3f * (num - 0.2f));
					float num3 = MathUtils.Saturate(0.2f * (20f - num));
					float num4 = num2 * num3;
					if (num4 > 0f)
					{
						if (m_batch == null)
						{
							m_batch = SubsystemParticles.PrimitivesRenderer.TexturedBatch(ContentManager.Get<Texture2D>(particle.Texture), false, 0, DepthStencilState.None);
						}
						Color color = particle.Color * num4;
						Vector2 size = particle.pSize;
						Vector3 p1 = particle.Position + right * size.X * -0.5f + down * size.Y * -0.5f;
						Vector3 p2 = particle.Position + right * size.X * 0.5f + down * size.Y * -0.5f;
						Vector3 p3 = particle.Position + right * size.X * 0.5f + down * size.Y * 0.5f;
						Vector3 p4 = particle.Position + right * size.X * -0.5f + down * size.Y * 0.5f;
						m_batch.QueueQuad(p1, p2, p3, p4, Vector2.Zero, new Vector2(1, 0), Vector2.One, new Vector2(0, 1), color);
					}
				}
			}
		}
	}
}
